package com.junlong0716.enjoylearning.ui

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ServiceUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.junlong0716.enjoylearning.CommentPresenter
import com.junlong0716.enjoylearning.MyApp
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.CommentAdapter
import com.junlong0716.enjoylearning.entity.CommentEntity
import com.junlong0716.enjoylearning.entity.RememberPlayVideoEntity
import com.junlong0716.enjoylearning.entity.SwitchVideoEntity
import com.junlong0716.enjoylearning.entity.rxevent.DownloadSucceedEvent
import com.junlong0716.enjoylearning.entity.rxevent.MusicPlayStateEvent
import com.junlong0716.enjoylearning.entity.rxevent.ProgressEvent
import com.junlong0716.enjoylearning.service.*
import com.junlong0716.enjoylearning.widget.PlayerBarView
import com.junlong0716.getknowledgedemo.decoration.DividerItemNoEndDecoration
import com.junlong0716.module.common.rxbus.RxBus
import com.junlong0716.module.common.rxbus.Subscribe
import com.junlong0716.module.common.rxbus.ThreadMode
import com.orhanobut.logger.Logger
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import io.realm.Realm
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.activity_video.*
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.regex.Pattern


class VideoActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var list: ArrayList<SwitchVideoEntity>
    private lateinit var commentData: ArrayList<CommentEntity.DataBean.ListBean>
    private lateinit var commentAdapter: CommentAdapter
    private lateinit var tvVideoName: TextView
    private lateinit var tvVideoDes: TextView
    private lateinit var tvBrowserNum: TextView
    private lateinit var tvVideoCreateDate: TextView
    private var videoId = 0
    private var source1 = ""
    private lateinit var ivPraise: ImageView
    private lateinit var tvLike: TextView
    private lateinit var rlLike: RelativeLayout
    private lateinit var author: String
    var orientationUtils: OrientationUtils? = null
    private lateinit var realm: Realm
    private var rememberPlayVideo: RememberPlayVideoEntity? = null
    private var currentDuring = 0L
    private var musicService: MusicService? = null
    private var mPlayerManager: PlayerManager? = null
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun downloadSucceed(downloadSucceedEvent: DownloadSucceedEvent) {
        if (videoId != downloadSucceedEvent.fileId) {
            return
        }
        fl_download.isClickable = false
        tv_download.text = "已下载"
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun downloadProgress(progressEvent: ProgressEvent) {
        if (videoId != progressEvent.knowledgeId) {
            return
        }
        fl_download.isClickable = false
        tv_download.text = "${(progressEvent.progress.fraction * 100).toInt()}%"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video)
        bindMyService()
        RxBus.getDefault().register(this)
        realm = Realm.getDefaultInstance()
        initData()
        initCommentList()
        initListener()



//        val commentPresenter = CommentPresenter()
//        commentPresenter.requestKnowledgeDetail(videoId, object : CommentPresenter.RequestKnowledgeDetailCallback {
//            override fun requestKnowledgeDetailsSucceed(knowledgeTitle: String, knowledgeContent: String, createDate: Long, browseNum: Int, isCollect: Int, isPraise: Int, praiseNum: Int, coverImg: String, author: String) {
//                if (isPraise == 1) {
//                    ivPraise.setBackgroundResource(R.mipmap.ic_love_sel)
//                    rlLike.isClickable = false
//                    tvLike.text = praiseNum.toString()
//                }
//            }
//        })
    }

    private fun initListener() {
        fl_download.setOnClickListener(this)
        fl_conform.setOnClickListener(this)
        fl_collection.setOnClickListener(this)
    }

    private fun initCommentList() {
        rv_list.layoutManager = LinearLayoutManager(this)
        commentAdapter = CommentAdapter(commentData, R.layout.item_comment)
        rv_list.adapter = commentAdapter
        rv_list.addItemDecoration(DividerItemNoEndDecoration(this, DividerItemNoEndDecoration.VERTICAL_LIST))
        val headerView = LayoutInflater.from(this).inflate(R.layout.item_video_comment_header, null)
        tvVideoName = headerView.findViewById<TextView>(R.id.tv_video_name)
        tvVideoDes = headerView.findViewById<TextView>(R.id.tv_video_description)
        tvBrowserNum = headerView.findViewById<TextView>(R.id.tv_play_count)
        tvVideoCreateDate = headerView.findViewById<TextView>(R.id.tv_video_create_date)
        val rlShare = headerView.findViewById<RelativeLayout>(R.id.rl_share)
        //tvVideoName.text = "商品科工作特色——小雪带你读“标准”第1期儿童服装选购注意事项"
        commentAdapter.addHeaderView(headerView)
        commentAdapter.setHeaderAndEmpty(true)

        val emptyView = LayoutInflater.from(this@VideoActivity).inflate(R.layout.view_empty, null)
        emptyView.findViewById<TextView>(R.id.tv_empty_content).text = "还没有人评论呢~ 快来抢沙发吧！"
        commentAdapter.emptyView = emptyView

        rlLike = headerView.findViewById<RelativeLayout>(R.id.rl_like)

        ivPraise = headerView.findViewById<ImageView>(R.id.tpv)
        tvLike = headerView.findViewById<TextView>(R.id.tv_like)
        rlLike.setOnClickListener(this)

        commentAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.ll_love_container -> {
                    val commentPresenter = CommentPresenter()
                    commentPresenter.requestAddCommentPraise(commentData[position].id, this, object : CommentPresenter.AddCommentPraiseCallback {
                        override fun requestAddCommentPraiseSucceed() {
                            requestCommentData()
                        }

                        override fun requestAddCommentPraiseFailed() {

                        }
                    })
                }

                R.id.tv_delete -> {
                    val commentPresenter = CommentPresenter()
                    commentPresenter.requestDelMyComment(this, commentData[position].id, object : CommentPresenter.DelMyCommentCallback {
                        override fun requestDelMyCommentFailed() {
                            ToastUtils.showShort("删除失败！")
                        }

                        override fun requestDelMyCommentSucceed() {
                            ToastUtils.showShort("删除成功！")
                            requestCommentData()
                        }
                    })
                }
            }
        }
        rlShare.setOnClickListener {
            val intent = Intent(this, ContactActivity::class.java)
            intent.putExtra("KNOWLEDGE_ID", videoId)
            startActivity(intent)
        }
    }

    private fun initData() {
        videoId = intent.getIntExtra("video_id", 0)
        source1 = intent.getStringExtra("video_url")

        try {
            author = intent.getStringExtra("video_author")
        } catch (e: Exception) {
            author = ""
        }

        val name = "普通"
        val switchVideoModel = SwitchVideoEntity(name, source1)

        val source2 = intent.getStringExtra("video_url")
        val name2 = "清晰"
        val switchVideoModel2 = SwitchVideoEntity(name2, source2)

        initVideoView(source1)

        list = ArrayList()
        list.add(switchVideoModel)
        list.add(switchVideoModel2)


        commentData = ArrayList()
//        commentData.add(CommentEntity("", "小雪", "文章写得真好！！", "", 10, 10, false))
//        commentData.add(CommentEntity("", "张作霖", "学习到了！！", "", 10, 10, false))
//        commentData.add(CommentEntity("", "小张", "这就是为什么国家会发展的这么迅速！", "", 10, 10, false))

        requestCommentData()
//        val map = HashMap<String, Any>()
//        map["knowledgeId"] = videoId
//        map["userId"] = MyApp.instance().userAccount!!.id
//        val jsonObject = JSONObject(map)


        val commentPresenter = CommentPresenter()
        commentPresenter.requestKnowledgeDetail(videoId, object : CommentPresenter.RequestKnowledgeDetailCallback {
            override fun requestKnowledgeDetailsSucceed(knowledgeTitle: String, knowledgeContent: String, createDate: Long, browseNum: Int, isCollect: Int, isPraise: Int, praiseNum: Int, coverImg: String, author: String, knowledgeDescribe: String, fileAddress: String) {
                if (isPraise == 1) {
                    ivPraise.setBackgroundResource(R.mipmap.ic_love_sel)
                    rlLike.isClickable = false
                    tvLike.text = praiseNum.toString()
                }
                tvVideoName.text = knowledgeTitle
                tvVideoDes.text = knowledgeDescribe
                tvBrowserNum.text = "播放量 ${browseNum}"
                if (author != "") {
                    tvVideoCreateDate.text = "${author}于${TimeUtils.millis2String(createDate, SimpleDateFormat("yyyy年MM月dd日"))}发布"
                } else {
                    tvVideoCreateDate.text = "${TimeUtils.millis2String(createDate, SimpleDateFormat("yyyy年MM月dd日"))}发布"

                }
                //val commentPresenter = CommentPresenter()
                if (commentPresenter.isDownloading("${tvVideoName.text}.mp4")) {
                    fl_download.isClickable = false
                    tv_download.text = "已下载"
                }
                if (isCollect == 0) {
                    tv_collection.text = "收藏"
                } else if (isCollect == 1) {
                    tv_collection.text = "已收藏"
                    fl_collection.isClickable = false
                }
            }
        })


//        OkGo.post<String>(REQUEST_HEADER + API_KNOWLEDGE_DETAIL)
//                .tag(this)
//                .upJson(jsonObject)
//                .execute(object : StringCallback() {
//                    override fun onSuccess(response: Response<String>?) {
//                        val jsonObj = JSONObject(response!!.body())
//                        val data = jsonObj.getJSONObject("data")
//                        val knowledgeTitle = data.getString("knowledgeTitle")
//                        val knowledgeDescribe = data.getString("knowledgeDescribe")
//                        val createDate = data.getLong("createDate")
//                        val browseNum = data.getInt("browseNumber")
//                        val isCollect = data.getInt("isCollect")
//                        tvVideoName.text = knowledgeTitle
//                        tvVideoDes.text = knowledgeDescribe
//                        tvBrowserNum.text = "播放量 ${browseNum}"
//                        if (author != "") {
//                            tvVideoCreateDate.text = "${author}于${TimeUtils.millis2String(createDate, SimpleDateFormat("yyyy年MM月dd日"))}发布"
//                        } else {
//                            tvVideoCreateDate.text = "${TimeUtils.millis2String(createDate, SimpleDateFormat("yyyy年MM月dd日"))}发布"
//
//                        }
//                        val commentPresenter = CommentPresenter()
//                        if (commentPresenter.isDownloading("${tvVideoName.text}.mp4")) {
//                            fl_download.isClickable = false
//                            tv_download.text = "已下载"
//                        }
//                        if (isCollect == 0) {
//                            tv_collection.text = "收藏"
//                        } else if (isCollect == 1) {
//                            tv_collection.text = "已收藏"
//                            fl_collection.isClickable = false
//                        }
//                    }
//                })


    }

    private fun initVideoView(source1: String?) {
        rememberPlayVideo = realm.where(RememberPlayVideoEntity::class.java).equalTo("videoId", videoId).findFirst()

        if (rememberPlayVideo == null) {
            realm.executeTransaction { it ->
                val rememberPlayVideoEntity = RememberPlayVideoEntity()
                rememberPlayVideoEntity.videoId = videoId
                rememberPlayVideoEntity.currentDuring = 0
                it.copyToRealm(rememberPlayVideoEntity)
            }
        } else {
            currentDuring = rememberPlayVideo!!.currentDuring!!
        }

        video_player.setUp(source1, true, "")
        //增加title
        video_player.getTitleTextView().setVisibility(View.VISIBLE)
        //设置返回键
        video_player.getBackButton().setVisibility(View.VISIBLE)

        //设置旋转
        orientationUtils = OrientationUtils(this, video_player)

        video_player.isRotateWithSystem = true;
        video_player.isRotateViewAuto = true

        video_player.fullscreenButton.setOnClickListener({
            //orientationUtils!!.screenType =
            video_player.isAutoFullWithSize = true
            orientationUtils!!.resolveByClick()
            video_player.startWindowFullscreen(this, false, true)
        })
        //设置返回按键功能
        video_player.backButton.setOnClickListener({
            onBackPressed()
        })
        video_player.isShowFullAnimation = true

        video_player.seekOnStart = currentDuring

        video_player.startPlayLogic()


        video_player.setGSYVideoProgressListener { progress, secProgress, currentPosition, duration ->
            if (progress == 99) {

                realm.executeTransaction { it ->
                    val rememberPlayMusicEntity = it.where(RememberPlayVideoEntity::class.java).equalTo("videoId", videoId).findFirst()
                    if (rememberPlayMusicEntity != null) {
                        rememberPlayMusicEntity.currentDuring = 0
                    }
                }
            }
        }

    }

    private fun requestCommentData() {
        val commentPresenter = CommentPresenter()
        commentPresenter.requestComment(this, 1, 20, videoId, object : CommentPresenter.RequestCommentCallback {
            override fun requestCommentSucceed(commentData: ArrayList<CommentEntity.DataBean.ListBean>) {
                if (commentData.isEmpty()) {
                    this@VideoActivity.commentData.clear()

                } else {
                    this@VideoActivity.commentData.clear()
                    this@VideoActivity.commentData.addAll(commentData)
                    commentAdapter.notifyDataSetChanged()
                }

                commentAdapter.notifyDataSetChanged()
            }
        })
    }


    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.fl_conform -> {
                val commentVal = edt_comment.text.toString().trim()
                val commentPresenter = CommentPresenter()
                if (!TextUtils.isEmpty(commentVal)) {
                    commentPresenter.requestAddComment(this, MyApp.instance().userAccount!!.id, videoId, commentVal, object : CommentPresenter.RequestAddCommentCallback {
                        override fun requestAddCommentSucceed() {
                            requestCommentData()
                            ToastUtils.showShort("评论成功！")
                            edt_comment.setText("")
                            if (KeyboardUtils.isSoftInputVisible(this@VideoActivity)) {
                                KeyboardUtils.hideSoftInput(this@VideoActivity)
                            }
                        }
                    })
                } else {
                    ToastUtils.showShort("请填写评论内容！")
                }
            }
            R.id.fl_download -> {

                if (ServiceUtils.isServiceRunning(FileDownloadService::class.java)) {
                    ToastUtils.showShort("有文件正在下载，请等待！")
                    return
                }

                val suffixes = "avi|mpeg|3gp|mp3|mp4|wav|jpeg|gif|jpg|png|apk|exe|pdf|rar|zip|docx|doc"
                val pat = Pattern.compile("[\\.]($suffixes)")//正则判断
                val mc = pat.matcher(source1)//条件匹配
                var fileSuffixes = ""
                while (mc.find()) {
                    fileSuffixes = mc.group()
                }
                val downloadIntent = Intent(this, FileDownloadService::class.java)
                downloadIntent.putExtra("FILE_URL", source1)
                downloadIntent.putExtra("FILE_NAME", "${tvVideoName.text}$fileSuffixes")
                downloadIntent.putExtra("FILE_ID", videoId)
                startService(downloadIntent)

            }
            R.id.fl_collection -> {
                val commentPresenter = CommentPresenter()
                commentPresenter.requestAddCollection(this, MyApp.instance().userAccount!!.id, videoId, object : CommentPresenter.RequestAddCollectionCallback {
                    override fun requestAddCollectionSucceed() {
                        tv_collection.text = "已收藏"
                        ToastUtils.showShort("收藏成功！")
                    }
                })
            }

            R.id.rl_like -> {
                val commentPresenter = CommentPresenter()
                commentPresenter.requestAddPraise(videoId, object : CommentPresenter.AddPraiseCallback {
                    override fun requestAddPraiseSucceed() {
                        ivPraise.setBackgroundResource(R.mipmap.ic_love_sel)
                        tvLike.text = (tvLike.text.toString().toInt() + 1).toString()
                        rlLike.isClickable = false
                    }
                })
            }
            else -> {
            }
        }
    }

    override fun onPause() {
        super.onPause()
        video_player.onVideoPause()

        val intent = Intent(this, RecordStudyEndService::class.java)
        intent.putExtra("KNOWLEDGE_ID",videoId)
        startService(intent)

    }

    override fun onResume() {
        super.onResume()
        video_player.onVideoResume()

        val commentPresenter = CommentPresenter()
        commentPresenter.requestAddStudyTime(this,videoId,object :CommentPresenter.AddStudyTimeCallback{
            override fun requestAddStudyTimeSucceed() {
                Logger.d("----------记录时间成功----------")
            }

            override fun requestAddStudyTimeFailed() {
                Logger.d("----------记录时间失败----------")
            }
        })
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    override fun onDestroy() {
        super.onDestroy()


        realm.executeTransaction { it ->
            val rememberPlayMusicEntity = it.where(RememberPlayVideoEntity::class.java).equalTo("videoId", videoId).findFirst()
            if (rememberPlayMusicEntity != null) {
                rememberPlayMusicEntity.currentDuring = video_player.currentPositionWhenPlaying.toLong()
            }
        }

        realm.close()


        GSYVideoManager.releaseAllVideos()

        if (orientationUtils != null)
            orientationUtils!!.releaseListener()

        if (RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().unregister(this)
        }

        unbindService(conn)
    }


    override fun onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(this)) {
            return
        }
        //释放所有
        video_player.setVideoAllCallBack(null)
        super.onBackPressed()
    }



    private var conn = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val myBinder = service as (MusicService.MyBinder)
            musicService = myBinder.getService()
            mPlayerManager = musicService!!.getPlayerManager()
            if (mPlayerManager!!.getCurrentMediaPlayerState()) {
                mPlayerManager!!.pauseMusic()
            }
        }
    }

    private fun bindMyService() {
        val intent = Intent(this, MusicService::class.java)
        bindService(intent, conn, AppCompatActivity.BIND_AUTO_CREATE)
    }
}
